import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col } from 'antd'
import { SearchOutlined } from "@ant-design/icons"
import { getHosListSearchParamsType,
  hospitalListContentType,
  hospitalListItemsType,
  getProvinceReturnType,
 
 } from '@/api/hospital/model/hospitalListTypes'
import {
   getHospitalListRequest,
  getProvinceRequest,
  getCityOrDistrictRequest,
  changeStatusRequest
} from '@/api/hospital/hospitalList'
import { use } from 'i18next'
import { useNavigate } from 'react-router-dom'





export default function HospitalList() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  //控制表格的是否加载中的状态
  const [isLoading, setIsLoading] = useState(false)
  //控制当前页码数量
  const [page, setPage] = useState(1)
  //控制每页显示条数
  const [limit, setLimit] = useState(3)
  //控制医院总数量
  const [total,setTotal] = useState(0)
  //控制查询的用户输入的表单参数
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>({})
  //控制表格的数据
  const [hospitalList,setHospitalList] = useState<hospitalListContentType>([])
  //省份控制初始值
  const [province,setProvince] =useState<getProvinceReturnType>([])
  //市级控制初始值
  const [cityList,setCityList] = useState<getProvinceReturnType>([])
  //设置县级
  const [district,setDistrict] = useState<getProvinceReturnType>([])
  //设置医院类型
  const[hospitalType,setHospitalType] = useState<getProvinceReturnType>([])
  //设置更新上线的状态
  const [status,setStatus] = useState(true)

  useEffect(() => {
    //匿名函数自调用
    (async function () {
      setIsLoading(true)
      const result = await getHospitalListRequest(page, limit, searchParams)
      //阿布结果content给数据
      setHospitalList(result.content)
      //拿到total数据
      setTotal(result.totalElements)
      setIsLoading(false)
    })()
  }, [searchParams,page,limit,status])

  useEffect(()=>{
    const getProvince= async ()=>{
     const result = await  getProvinceRequest()
     setProvince(result)
    }
    getProvince()
  },[])
  //事件回调函数
  //1.省份变化函数
  const changeProviceHandle=(vaule:string)=>{
        ( async   function(){
          const result = await  getCityOrDistrictRequest(vaule)
          setCityList(result)
          //当点击新的页面的省份的时候 从新加载 
        form.setFieldsValue({cityCode:null,districtCode:null})
        //清空县级数据
        setDistrict([])
        })()
  }
  //2.城市变化函数
  const changeCityHandle=(vaule:string)=>{
    ( async function(){
      const result = await  getCityOrDistrictRequest(vaule)
      setDistrict(result)
      //当点击新的城市的时候 重新加载
      form.setFieldsValue({ districtCode:null})
    })()
  }
  //3.提交表单事件
  const finishHandle = ( value:getHosListSearchParamsType)=>{
    setSearchParams(value)
  }
  //4.清空列表
  const clearSearchHandle =()=>{
    setSearchParams({})
  }
  //5.医院类型请求
  useEffect(()=>{
    const getHospitalType = async ()=>{
      const result = await getCityOrDistrictRequest('10000')
      setHospitalType(result)
    }
    getHospitalType()
  },[])
  //6.0查询跳转
  const hospitalDetailHandle=(id:string)=>{
   return ()=>{
    navigate(`/syt/hospital/hospitalShow/${id}`)
   }
  }
  //7.上线和下线请求
  const changeStateHandle = (id:string,num:0|1)=>{
      return async ()=>{
        await changeStatusRequest(id,num)
        setStatus(!status)
      }
  }
//表格字段
  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render(logoData:string){
        return(
          <img width={100} src={`data:image/jpeg;base64,${logoData}`} alt='logo'></img>
        )
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(_:any,data:hospitalListItemsType){
        return data.param.hostypeString
      }
    },
    {
      title: '详细地址',
      render(_:any,data:hospitalListItemsType){
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      render(_:any,data:hospitalListItemsType){
        return data.status ===0 ?'下线':'上线'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any,data:hospitalListItemsType) {
        const {id} =data
        return (
          <div>
            <Button type='primary'  onClick={hospitalDetailHandle(id)}>查看</Button>
            <Button type='primary' onClick={()=>{navigate(`/syt/hospital/hospitalSchedule/${data.hoscode}`)}}>排班</Button>
            <Button type='primary' onClick={changeStateHandle(data.id,data.status === 0 ?1:0)}>{data.status === 0 ?'上线':'下线'}</Button>
          </div >
        )
      }
    }
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          form={form}
          onFinish={finishHandle}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={changeProviceHandle}
                >
                  {
                    province.map(item=>{
                      return <Select.Option value={item.value}  key={item.id}>{item.name}</Select.Option>
                    })
                  }

                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={changeCityHandle}
                >
                  {
                    cityList.map(item=>{
                      return <Select.Option value={item.value}  key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {
                    district.map(item=>{
                      return <Select.Option value={item.value}  key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    hospitalType.map(item=>{
                      return <Select.Option value={item.value}  key={item.id}>{item.name}</Select.Option>
                    })
                  }

                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col >

            <Col span={2}>
              <Form.Item >
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>

            </Col>
            <Col span={2} style={{ marginLeft: "20px" }}>
              <Form.Item >
                <Button type="default" htmlType="reset"  onClick={clearSearchHandle}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>



        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}

          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`
            },
            onChange(page:number,pageSize:number){
              setPage(page)
              setLimit(pageSize)
            }
          }}
        />
      </Card>
    </div >
  )
}

